
package com.borqs.music.tasks;

import static com.borqs.music.http.RequestMethod.GET;
import static com.borqs.music.util.MusicConf.ReqParam.AREA;
import static com.borqs.music.util.MusicConf.ReqParam.COUNT;
import static com.borqs.music.util.MusicConf.ReqParam.PAGE;
import static com.borqs.music.util.MusicConf.ReqParam.SORT;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpRequest;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.model.SingerInfo;
import com.borqs.music.util.MusicConf;
import com.borqs.music.util.MusicConf.ReqType;

public class GetSingerListTask extends Task {
    public static final int DEFAULT_COUNT = 20;
    private String mTicket;
    private String mSort;
    private int mPage;
    private int mArea;

    public GetSingerListTask(TaskListener getSingerListListener, String ticket, String sort, int page,
            int area) {
        super(getSingerListListener);
        this.mTicket = ticket;
        this.mSort = sort;
        this.mPage = page;
        this.mArea = area;
    }

    public GetSingerListTask(TaskListener getSingerListListener, String ticket, int page, int area) {
        this(getSingerListListener, ticket, "", page, area);
    }

    @Override
    public HttpRequest prepareRequest() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(SORT, mSort);
        params.put(PAGE, String.valueOf(mPage));
        params.put(COUNT, String.valueOf(DEFAULT_COUNT));
        params.put(AREA, String.valueOf(mArea));
        
        String url = MusicConf.getUrl(ReqType.MUSIC_SINGERS);
        HttpRequest req = new HttpRequest(GET, url, mTicket, params);
        return req;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        checkResponse(resp);
        JSONArray jArr = resp.asJSONArray();
        List<SingerInfo> singers = decodeSingersJSONArray(jArr);
        return singers;
    }

    private List<SingerInfo> decodeSingersJSONArray(JSONArray jArr) throws JSONException {
        List<SingerInfo> singers = new ArrayList<SingerInfo>(10);
        for (int i = 0, len = jArr.length(); i < len; i++) {
            JSONObject jObj;
            jObj = jArr.getJSONObject(i);
            SingerInfo singer = new SingerInfo();
            singer.id = jObj.getInt("singer_id");
            singer.name = jObj.getString("singer_name");
            singer.imgUrl = jObj.getString("photo_url");
            singers.add(singer);
        }
        return singers;
    }
}
